﻿using System;
using System.Linq;
using System.Web.Mvc;
using BLL;
using Model;
using Web.Helper;


namespace Web.Areas.Manager.Controllers
{
    [UserAuthorize]
    public class AddressBookController : Controller
    {
        AddressBook_BLL _AddressBook_BLL = new AddressBook_BLL();
        AddressBookType_BLL _AddressBookType_BLL = new AddressBookType_BLL();
        Sys_Users_BLL _Sys_Users_BLL = new Sys_Users_BLL();

        public virtual ActionResult Index(int? pageIndex, string keyword)
        {
            var model = _AddressBook_BLL.Get().Where(a => a.Sys_Users.Id.Equals(new Guid(User.Identity.Name)));
            if (!string.IsNullOrEmpty(keyword))
            {
                model = model.Where(a => a.ContactName.Contains(keyword) || a.ContactTitle.Contains(keyword) || a.CompanyName.Contains(keyword) || a.MobilePhoneNumber.Contains(keyword) || a.TelephoneNumber.Contains(keyword));
            }
            return View(model.ToPagedList(pageIndex));
        }

        public virtual ActionResult Details(Guid Id)
        {
            ViewBag.AddressBookType = _AddressBookType_BLL.Get();
            var item = _AddressBook_BLL.Get(Id);
            return View(item);
        }

        public virtual ActionResult Edit(Guid? Id)
        {
            ViewBag.AddressBookType = _AddressBookType_BLL.Get();
            if (_AddressBookType_BLL.Get().Count() == 0)
            {
                Response.Write("<script>alert('请先添加通讯薄类型')</script>");
                Response.End();
            }
            var item = _AddressBook_BLL.Get(Id);
            return View(item);
        }

        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Edit(Guid? Id, AddressBook collection)
        {
            
            if (!ModelState.IsValid)
            {
                ViewBag.AddressBookType = _AddressBookType_BLL.Get();
                return View(collection);
            }

          //  collection.UserId = _Sys_Users_BLL.Get(User.Identity.Name).Id;

            _AddressBook_BLL.Save(Id, ref collection);


            return RedirectToAction("Index", MyrouteValues.Get());
        }

        [HttpDelete]
        public virtual ActionResult Delete(Guid Id)
        {
            _AddressBook_BLL.Delete(Id);
            return RedirectToAction("Index", new { pageIndex = Request["pageIndex"], keyword = Request["keyword"] });
        }
    }
}
